/** Cloudflare:outlook-worker[query-zea]
 * 功能：Firefox自动登录Lunes [betadash.lunes.host]
 * Zeabur:rtian002[Firefox]
 * KV: mydata[zea] 保存用户信息
 * - DOMAIN: zea.req.xx.kg
 * - https://zea.req.xx.kg 默认每天获取一个用户sid[serviceID]
 * - https://zea.req.xx.kg/[username] 获取指定用户sid
 * - https://zea.req.xx.kg/[username]?cmd=start 启动[start]或停止[stop]默认用户（或指定用户）的服务器
 * 
 * - Zeabur API ：https://studio.apollographql.com/public/zeabur/variant/main/explorer
 * 
 * 目前：admini@ct8 使用shell脚本做计划任务
 * 
 * Cloudflare 免费账户仅限5个计划任务
 * 
 */

export default {
  async fetch(request, env, ctx) {
    const { token, envid, sids } = await getinfo(env);
    const url = new URL(request.url);
    var username = url.pathname.slice(1);
    if (!(username in sids)) {
      const today = new Date()
      const wk = today.getDay();
      const users = Object.keys(sids)
      username = users[wk]
    }
    const sid = sids[username]
    const command = url.searchParams?.get('cmd') || ''
    if (command && command.match(/start|stop/)) {
      await process(token, envid, sid, command)
      return Response.json({ username, token, envid, sid, command })
    } else {
      return new Response(sid)
    }
  },//fetch


/**
 * 计划任务： 每天
 * 目前：cloudflare未设置
 */
  async scheduled(event, env, ctx) {
    console.log(event.scheduledTime)
    const { token, envid, sids } = await getinfo(env);
    const today = new Date(event.scheduledTime)
    const wk = today.getDay();
    const hh=today.getHours();
    const users = Object.keys(sids)
    const username = users[wk]
    const sid = sids[username]

    // 计划执行时间每天设置两个小时，如：11点11分重启服务，12点11分关闭服务 
    // cron： 11 11,12 * * * 
    const command=hh%2?"start":"stop" 
    console.log({ username, token, envid, sid, command })
    await process(token, envid, sid, command)
  }
};
async function getinfo(env) {
  const mydata = await env.KV.get('zea');
  const hosts = JSON.parse(mydata)
  const token = hosts['rtian002']['TOKEN']
  const envid = hosts['rtian002']['ENVID']
  const sids = hosts['rtian002']['SERV']
  return { token, envid, sids }
}

async function process(token, envid, sid, command) {
  const api = 'https://api.zeabur.com/graphql';
  const _cmd = { 'start': 'restartService', 'stop': 'suspendService' }
  let data = {
    "query": `mutation Mutation {
        ${_cmd[command]}(serviceID: "${sid}", environmentID: "${envid}")
        }`
  }
  await fetch(api, {
    method: 'POST',
    headers: {
      "Authorization": `Bearer ${token}`,
      "content-type": "application/json"
    },
    body: JSON.stringify(data)
  })
}//process